package bhwz.seac3.db.nbadata;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;

import bhwz.seac3.db.Database;
import bhwz.seac3.dbservice.nbadata.SeasonDBService;
import bhwz.seac3.po.PlayerPo;
import bhwz.seac3.po.TeamPo;

public class SeasonDB implements SeasonDBService {

	@SuppressWarnings("unchecked")
	@Override
	/**
	 * 所有返回的Season按照时间降序排列，最近赛季的index为0
	 */
	public List<String> queryAllSeasons() throws Exception {
		List<String> result = new ArrayList<String>();
		Database.executeTransaction(s -> {
			Query q = s
					.createQuery("select distinct match.season from MatchPo match");
			q.list().forEach(e -> result.add((String) e));
		});
		sortDesc(result);
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	/**
	 * 所有返回的Season按照时间降序排列，最近赛季的index为0
	 */
	public List<String> queryJoinedSeasons(PlayerPo player) throws Exception {
		List<String> result = new ArrayList<String>();
		Database.executeTransaction(s -> {
			Query q1 = s
					.createQuery("select distinct match.season from MatchPo match,PlayerScoreTablePo score where score in elements(match.team1PlayersScore) and score.球员名=?)");
			q1.setString(0, player.getName());
			q1.list().forEach(e -> result.add((String) e));
			Query q2 = s
					.createQuery("select distinct match.season from MatchPo match,PlayerScoreTablePo score where score in elements(match.team2PlayersScore) and score.球员名=?)");
			q2.setString(0, player.getName());
			q2.list().forEach(e -> {
				if (!result.contains(e))
					result.add((String) e);
			});
		});
		sortDesc(result);
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	/**
	 * 所有返回的Season按照时间降序排列，最近赛季的index为0
	 */
	public List<String> queryJoinedSeasons(TeamPo team) throws Exception {
		List<String> result = new ArrayList<String>();
		Database.executeTransaction(s -> {
			Query q1 = s
					.createQuery("select distinct match.season from MatchPo match where match.team1=?");
			q1.setString(0, team.get缩写());
			q1.list().forEach(e -> result.add((String) e));
			Query q2 = s
					.createQuery("select distinct match.season from MatchPo match where match.team2=?");
			q2.setString(0, team.get缩写());
			q2.list().forEach(e -> {
				if (!result.contains(e))
					result.add((String) e);
			});
		});
		sortDesc(result);
		return result;
	}

	private void sortDesc(List<String> seasons){		
		seasons.sort((String s1,String s2)->(praseFirstYear(s2)-praseFirstYear(s1)));
	}
	
	private int praseFirstYear(String season){
		final int maxYear=40;
		int firstYear= Integer.parseInt(season.split("-")[0]);
		if(firstYear>maxYear){
			firstYear=firstYear-100;
		}
		return firstYear;
	}
}
